'use strict';

const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');
const awaitWriteStream = require('await-stream-ready').write;

class UploadController extends Controller {
  async uploadFile() {
    const { ctx } = this;
    const stream = await ctx.getFileStream();
    const filename = stream.filename;
    const writeStream = fs.createWriteStream(path.join('app/public/uploads', filename))
    if (!fs.existsSync('app/public/uploads')) {
      fs.mkdirSync('app/public/uploads')
    }
    try {
      // 文件写入
      await awaitWriteStream(stream.pipe(writeStream));
      this.ctx.status = 200;
    } catch (error) {
      console.log(error)
    }
  }
}

module.exports = UploadController;
